package cn.ibizlab.util.adapter.service.impl;

import cn.ibizlab.util.security.AuthenticationUser;
import net.ibizsys.central.cloud.core.security.SystemAccessManager;
import net.ibizsys.central.security.ISysUserRoleRuntime;
import net.ibizsys.runtime.security.IUserContext;
import net.ibizsys.runtime.util.IEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限适配
 *
 * @author xignzi
 * @date 2024/3/5
 */
public class DefaultAdapterSystemAccessManager extends SystemAccessManager {


    @Override
    public List<ISysUserRoleRuntime> getSysUserRoleRuntimes(IUserContext iUserContext) {
        List<ISysUserRoleRuntime> assignSysUserRoleRuntimeList = new ArrayList<>();
        AuthenticationUser curUser = AuthenticationUser.getAuthenticationUser();
        if (curUser == null) {

            return assignSysUserRoleRuntimeList;
        }
        if (ObjectUtils.isEmpty(curUser.getAuthorities())) {
            return assignSysUserRoleRuntimeList;
        }

        for (GrantedAuthority ga : curUser.getAuthorities()) {
            ISysUserRoleRuntime iSysUserRoleRuntime = this.getSysUserRoleRuntime(ga.getAuthority(), true);
            if (iSysUserRoleRuntime != null) {
                assignSysUserRoleRuntimeList.add(iSysUserRoleRuntime);
            }
        }
        return assignSysUserRoleRuntimeList;
    }

    @Override
    public boolean testSysUniRes(IUserContext iUserContext, String strSysUniRes, IEntity iEntity) throws Exception {
        AuthenticationUser curUser = AuthenticationUser.getAuthenticationUser();
        if (curUser != null) {
            if (curUser.isSuperUser())
                return true;
        }
        return super.testSysUniRes(iUserContext, strSysUniRes, iEntity);
    }

}
